<template>
    <div class="user-management-page">
        <div class="operation-bar">
            <el-button type="primary" size="small" @click="addUser">添加用户</el-button>

            <div class="filter-container">
                <el-input v-model="searchEmail" placeholder="请输入邮箱查询" size="small" clearable @clear="handleSearch"
                    @keyup.enter.native="handleSearch" style="width: 200px;" />
                <el-button type="primary" size="small" @click="handleSearch">查询</el-button>
            </div>
        </div>

        <div class="table-wrapper">
            <el-table :data="tableData" stripe :row-key="row => row.id" class="table-content">
                <el-table-column prop="email" label="邮箱" header-align="center" align="center" width="150" />
                <el-table-column prop="role" label="角色" header-align="center" align="center" :formatter="formatRole" />
                <el-table-column label=" 账号状态" header-align="center" align="center">
                    <template #default="{ row }">
                        <el-switch v-model="row.status" :active-value="1" :inactive-value="0"
                            @change="handleStatusChange(row)" :disabled="row.is_deleted === 1" />
                    </template>
                </el-table-column>
                <el-table-column prop="is_deleted" label="是否删除" header-align="center" align="center">
                    <template #default="{ row }">
                        <span :class="row.is_deleted === 1 ? 'deleted-tag' : 'normal-tag'">
                            {{ row.is_deleted === 1 ? '已删除' : '正常' }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="last_login_ip" label="登录IP" header-align="center" align="center" />
                <el-table-column prop="last_login_at" label="上次登录时间" :formatter="formatDate" header-align="center"
                    align="center" width="180"/>

                <el-table-column label="操作" fixed="right" header-align="left" align="left" width="240">
                    <template #default="{ row }">
                        <el-button type="primary" size="small" @click="handleEdit(row)"
                            :disabled="row.is_deleted === 1">修改</el-button>
                        <el-button type="info" size="small" @click="handleResetPwd(row)"
                            :disabled="row.is_deleted === 1">重置密码</el-button>
                        <el-button type="danger" size="small" @click="handleDelete(row)"
                            :disabled="row.is_deleted === 1">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <div class="pagination-container">
            <el-pagination background layout="sizes, prev, pager, next, jumper, ->, total" :page-sizes="[5, 10, 20, 50]"
                :page-size="pageSize" :current-page="currentPage" :total="total" @current-change="handlePageChange"
                @size-change="handleSizeChange" />
        </div>

        <!-- 添加用户弹窗 -->
        <el-dialog title="添加用户" v-model="showAddDialog" width="30%" :before-close="handleAddDialogClose">
            <el-form :model="addForm" ref="addFormRef" label-width="60px" :rules="rules">
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addForm.email" autocomplete="off" />
                </el-form-item>

                <el-form-item label="角色" prop="role">
                    <el-select v-model="addForm.role" placeholder="请选择角色">
                        <el-option label="超级管理员" value="super_admin" />
                        <el-option label="用户" value="user" />
                        <el-option label="访客" value="visitor" />
                    </el-select>
                </el-form-item>
            </el-form>

            <template #footer>
                <el-button @click="handleAddCancel">取消</el-button>
                <el-button type="primary" @click="submitAddForm">确定</el-button>
            </template>
        </el-dialog>

        <!-- 修改用户弹窗 -->
        <el-dialog title="修改用户" v-model="showEditDialog" width="30%" :before-close="handleEditDialogClose">
            <el-form :model="editForm" ref="editFormRef" label-width="60px" :rules="rules">
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editForm.email" autocomplete="off" />
                </el-form-item>

                <el-form-item label="角色" prop="role">
                    <el-select v-model="editForm.role" placeholder="请选择角色" :disabled="editForm.role === 'super_admin'">
                        <el-option label="用户" value="user" />
                        <el-option label="访客" value="visitor" />
                        <el-option v-if="editForm.role === 'super_admin'" label="超级管理员" value="super_admin" />
                    </el-select>
                </el-form-item>

            </el-form>

            <template #footer>
                <el-button @click="handleEditCancel">取消</el-button>
                <el-button type="primary" @click="submitEditForm">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUsersAPI, addUserAPI, updateUserAPI, deleteUserAPI, updateUserStatusAPI, resetPasswordAPI } from '@/api/user'

const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(5)
const searchEmail = ref('')
const total = ref(0)
const tableData = ref([])

const showAddDialog = ref(false)
const addFormRef = ref(null)
const addForm = reactive({
    email: '',
    role: '',
})

const showEditDialog = ref(false)
const editFormRef = ref(null)
const editForm = reactive({
    id: null,
    email: '',
    role: '',
})

const rules = {
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] },
    ],
    role: [{ required: true, message: '请选择角色', trigger: 'change' }],
}

const formatDate = (row, column, cellValue) => {
    if (!cellValue) return ''
    const date = new Date(cellValue)
    const pad = (n) => n.toString().padStart(2, '0')

    const year = date.getFullYear()
    const month = pad(date.getMonth() + 1)
    const day = pad(date.getDate())
    const hours = pad(date.getHours())
    const minutes = pad(date.getMinutes())
    const seconds = pad(date.getSeconds())

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

const formatRole = (row, column, cellValue) => {
    const map = {
        super_admin: '超级管理员',
        user: '用户',
        visitor: '访客',
    }
    return map[cellValue] || cellValue
}

const fetchData = async () => {
    try {
        loading.value = true
        const params = {
            page: currentPage.value,
            page_size: pageSize.value,
            search_name: searchEmail.value,
        }
        const res = await getUsersAPI(params)
        total.value = res.total
        tableData.value = res.users
    } catch (error) {
        console.error('获取用户列表失败', error)
        // ElMessage.error('获取用户列表失败')
    } finally {
        loading.value = false
    }
}

const handlePageChange = (page) => {
    currentPage.value = page
    fetchData()
}

const handleSizeChange = (size) => {
    pageSize.value = size
    currentPage.value = 1
    fetchData()
}

const handleSearch = () => {
    currentPage.value = 1
    fetchData()
}

const addUser = () => {
    resetAddForm()
    showAddDialog.value = true
}

const resetAddForm = () => {
    addForm.email = ''
    addForm.role = ''
    addFormRef.value?.clearValidate()
}

const submitAddForm = () => {
    addFormRef.value.validate(async (valid) => {
        if (valid) {
            try {
                await addUserAPI({ email: addForm.email, role: addForm.role })
                ElMessage.success('添加用户成功')
                showAddDialog.value = false
                fetchData()
                resetAddForm()
            } catch (error) {
                console.error('添加用户失败')
            }
        }
    })
}

const handleAddCancel = () => {
    resetAddForm()
    showAddDialog.value = false
}


const handleEdit = (row) => {
    editForm.id = row.id
    editForm.email = row.email
    editForm.role = row.role
    showEditDialog.value = true
}

const handleResetPwd = async (row) => {
    try {
        await ElMessageBox.confirm(`确定要重置用户 ${row.email} 的密码吗？`, '重置密码确认', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        })
        await resetPasswordAPI(row.id)
        ElMessage.success(`用户 ${row.email} 密码已重置`)
    } catch (err) {
        if (err !== 'cancel') {
            console.error('重置密码失败')
        } else {
            ElMessage.info('已取消重置')
        }
    }
}

const resetEditForm = () => {
    editForm.id = null
    editForm.email = ''
    editForm.role = ''
    editFormRef.value?.clearValidate()
}

const submitEditForm = () => {
    editFormRef.value.validate(async (valid) => {
        if (valid) {
            try {
                await updateUserAPI(editForm.id, {
                    email: editForm.email,
                    role: editForm.role,
                })
                ElMessage.success('修改用户成功')
                showEditDialog.value = false
                fetchData()
                resetEditForm()
            } catch (error) {
                console.error('修改用户失败')
            }
        }
    })
}

const handleEditCancel = () => {
    resetEditForm()
    showEditDialog.value = false
}

const handleDelete = async (row) => {
    try {
        await ElMessageBox.confirm(`确定删除用户 ${row.email} 吗？（软删除）`, '删除确认', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        })
        await deleteUserAPI(row.id)
        ElMessage.success(`用户 ${row.email} 已软删除`)
        fetchData()
    } catch (err) {
        if (err !== 'cancel') {
            console.error('删除失败')
        } else {
            ElMessage.info('已取消删除')
        }
    }
}


const handleStatusChange = async (row) => {
    try {
        await updateUserStatusAPI(row.id, { status: row.status })
        ElMessage.success({
            message: row.status === 1 ? '账号已启用' : '账号已禁用',
            duration: 1000,
        });
    } catch (error) {
        console.error(error)
    }
}


onMounted(async () => {
    await fetchData()
})
</script>

<style scoped>
/* 用户是否删除标签样式 */
.normal-tag {
    display: inline-block;
    padding: 2px 12px;
    border-radius: 12px;
    background: #4caf50;
    color: #fff;
    font-weight: bold;
    font-size: 13px;
    min-width: 48px;
    text-align: center;
}

.deleted-tag {
    display: inline-block;
    padding: 2px 12px;
    border-radius: 12px;
    background: #ccc;
    color: #fff;
    font-weight: bold;
    font-size: 13px;
    min-width: 48px;
    text-align: center;
}

.user-management-page {
    width: 100%;
    box-sizing: border-box;
}

.operation-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
}

.filter-container {
    display: flex;
    gap: 10px;
    align-items: center;
}

/* 统一输入框内部 input 高度和按钮高度一致 */
.filter-container .el-input input {
    height: 28px !important;
    line-height: 28px !important;
    padding: 0 10px !important;
}

.pagination-container {
    margin-top: 20px;
    text-align: right;
}


.table-wrapper {
    overflow-x: auto;
    scrollbar-width: thin;
    scrollbar-color: #888 #f1f1f1;
}

.table-content {
    width: 100%;
    min-width: 1000px;
}

.table-wrapper::-webkit-scrollbar {
    height: 8px;
}

.table-wrapper::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
}

.table-wrapper::-webkit-scrollbar-thumb {
    background-color: #888;
    border-radius: 4px;
    border: 2px solid #f1f1f1;
}

.table-wrapper::-webkit-scrollbar-thumb:hover {
    background-color: #555;
}

.normal-tag {
    display: inline-block;
    padding: 2px 12px;
    border-radius: 12px;
    background: #4caf50;
    color: #fff;
    font-weight: bold;
    font-size: 13px;
    min-width: 48px;
    text-align: center;
}

.deleted-tag {
    display: inline-block;
    padding: 2px 12px;
    border-radius: 12px;
    background: #ccc;
    color: #fff;
    font-weight: bold;
    font-size: 13px;
    min-width: 48px;
    text-align: center;
}
</style>
